﻿@model Auction_Intranet.Models.StatisticModel
@{
    ViewBag.Title = "Statistics";
}

<script src="@Url.Content("~/Scripts/highcharts.js")"></script>
<script src="@Url.Content("~/Scripts/modules/exporting.js")"></script>               
<script src="@Url.Content("~/Scripts/Statistics.js")" type="text/javascript"></script>

<div class="page statistics-index">
    <h2>Average bid amount per time slot
        <span class="bids-week-paging stats-nav">
            <span class="loading-icon-stats-week"></span>
            <span class="prev"><a href="#" title="Previous week"></a></span>
            <span class="current">@Model.averageBiddedDay.roomStatistics.First().day.ToLongDateString() - @Model.averageBiddedDay.roomStatistics.Last().day.ToLongDateString()</span>
            @{ var currentDate = DateTime.Now.Date; var displayDate = Model.currentDateResult.Date; }
            @if (displayDate < currentDate)
            {
                <span class="next"><a href="#" title="Next day"></a></span>
            }                          
        </span>    
    </h2>
    <div id="containeraverage"></div>
    <h2>Most popular hours 
        <span class="bids-date-paging stats-nav">
            <span class="loading-icon-stats"></span>
            <span class="prev"><a href="#" title="Previous day"></a></span>
            <span class="current">@Model.mostlyBiddedHour.date.ToLongDateString()</span>
            <span><input style="display: none;" title="stat date" type="text" class="stat-datepicker" /></span>
            <span class="next"><a href="#" title="Next day"></a></span>                                                                      
        </span>
    </h2>    
    <div id="container"></div>
</div>

<table id="datatableaverage" style="display:none;">
	<thead>
		<tr>
			<th></th>
			<th>Average bid amount per time unit</th>
		</tr>
	</thead>
	<tbody>
        @foreach (var item in Model.averageBiddedDay.roomStatistics)
        {
            if (item.day.Date > Model.currentDateResult.Date)
            {
		    <tr>
			    <th>@item.abbreviation @item.day.Day</th>
			    <td></td>
		    </tr> 
            }
            else
            { 
		    <tr>
			    <th>@item.abbreviation @item.day.Day</th>
			    <td>@item.avgPerTime</td>
		    </tr>             
            }
        } 
	</tbody>
</table>

<table id="datatable" style=" display: none; ">
	<thead>
		<tr>
			<th></th>
			<th>Number of bids per time</th>
		</tr>
	</thead>
	<tbody>
        @foreach (var item in Model.mostlyBiddedHour.timeStatistics)
        { 
		    <tr>
			    <th>@item.time</th>
			    <td>@item.numberOFBids</td>
		    </tr>                    
        }
	</tbody>
</table>

<script type="text/javascript">

$(function () {

    chartStatistics_Average();
    chartStatistics();

    var today = new Date();
    var currentDate = new Date(@Model.currentDateResult.Year,@Model.currentDateResult.Month-1,@Model.currentDateResult.Day,@Model.currentDateResult.Hour,@Model.currentDateResult.Minute,@Model.currentDateResult.Second,@Model.currentDateResult.Millisecond);                
    var currentDateMostPopular = new Date(@Model.mostlyBiddedHour.date.Year,@Model.mostlyBiddedHour.date.Month-1,@Model.mostlyBiddedHour.date.Day,@Model.mostlyBiddedHour.date.Hour,@Model.mostlyBiddedHour.date.Minute,@Model.mostlyBiddedHour.date.Second,@Model.mostlyBiddedHour.date.Millisecond);                
               
    var currentWeekMonday = new Date(@Model.averageBiddedDay.date.Year,@Model.averageBiddedDay.date.Month-1,@Model.averageBiddedDay.date.Day,@Model.averageBiddedDay.date.Hour,@Model.averageBiddedDay.date.Minute,@Model.averageBiddedDay.date.Second,@Model.averageBiddedDay.date.Millisecond);                        
    var currentWeekMax = @Model.averageBiddedDay.week;
    var currentAllowDate = new Date(@Model.currentDateResult.Year,@Model.currentDateResult.Month-1,@Model.currentDateResult.Day,@Model.currentDateResult.Hour,@Model.currentDateResult.Minute,@Model.currentDateResult.Second,@Model.currentDateResult.Millisecond);                
    var canNext = false;     

    /***************************************/
    $(".bids-week-paging .prev a").click(function (event) {
        event.preventDefault();                        
        $(".loading-icon-stats-week").show();            
        var ticks = date_by_subtracting_days(currentWeekMonday,7).getTime();
        updateWeekStatResults(ticks);

    });
    $(".bids-week-paging .next a").live("click", function (event) {
        event.preventDefault();
        $(".loading-icon-stats-week").show();            
        var ticks = date_by_adding_days(currentWeekMonday,7).getTime();
        updateWeekStatResults(ticks);        
    });          
        
    /**************************************/
    $(".bids-date-paging .prev a").click(function (event) {
        event.preventDefault();                        
        //console.log("getting prev: " + date_by_subtracting_days(currentDate,1));
        $(".loading-icon-stats").show();
        var ticks = date_by_subtracting_days(currentDateMostPopular,1).getTime();            
        updateStatResults(ticks);

    });
    $(".bids-date-paging .next a").live("click", function (event) {
        event.preventDefault();
        //console.log("getting next: " + date_by_adding_days(currentDate,1));
        $(".loading-icon-stats").show();
        var ticks = date_by_adding_days(currentDateMostPopular,1).getTime();
        updateStatResults(ticks);
    });
    /****************************************/                  
    $( ".stat-datepicker" ).datepicker({
        dateFormat: 'mm/dd/yy',
        showOn: "button",
        //buttonImage: "../../Content/images/icons/datepicker-cal.png",
        buttonImage: "../../Content/images/icons/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Stat date",
        onSelect: function( selectedDate ) {
            $(".loading-icon-stats").show();            
            var selectedDate = new Date(selectedDate);
            var ticks = selectedDate.getTime();
            updateStatResults(ticks);
        }
    });
    /****************************************/                      

    function updateWeekStatResults(dateticks) {             
        $.ajax({
            type: 'POST',
            /*async: false,*/
            url: "/Statistics/ChartWeekAJAX",
            dataType: "json",
            data: { ticks: dateticks },
            success: function (data) {
                if (data !== "") {                
                    ctn = 0;                    
                    $("#datatableaverage tbody tr").each(function () {
                        var tempDate = new Date(data[ctn].realYear,data[ctn].realMonth-1,data[ctn].realDay,0,0,0);                        
                        if(tempDate > currentAllowDate){
                            $(this).find("th").text(data[ctn].day);
                            $(this).find("td").text("");                               
                        }
                        else {
                            $(this).find("th").text(data[ctn].day);
                            $(this).find("td").text(data[ctn].avgPerTime);                            
                        }
                        ctn++;
                    });
                    //update dates and links
                    var m_names = new Array("January", "February", "March", 
                    "April", "May", "June", "July", "August", "September", 
                    "October", "November", "December");
                    var newdate = new Date(dateticks);                     
                    var newDateEnd = date_by_adding_days(newdate,6);           
                    $(".bids-week-paging .current").text(newdate.getDate() + " " + m_names[newdate.getMonth()] + " " + newdate.getFullYear() + " - " + newDateEnd.getDate() + " " + m_names[newDateEnd.getMonth()] + " " + newDateEnd.getFullYear());                    
                    currentWeekMonday = newdate;                                                                
                    chartStatistics_Average();
                    //allow next (future) lookup or not
                    var tempRequestDate = date_by_adding_days(currentWeekMonday,7);
                    if (tempRequestDate <= currentAllowDate) {
                        if(canNext == false) {
                            var elem = document.createElement("span");
                            $(elem).attr("class", "next");
                            var anchor = document.createElement("a");
                            $(anchor).attr("href", "#");
                            $(anchor).attr("title", "Next day");
                            $(elem).append(anchor);
                            $(".bids-week-paging").append(elem);
                            canNext = true;
                        }
                    }
                    else {                        
                        $(".bids-week-paging .next").remove();
                        canNext = false;
                    }
                }
                else {                    
                    $(".bids-week-paging .next").hide();
                    canNext = false;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $(".loading-icon-stats-week").hide();
                alert(xhr.status);
                alert(thrownError);
            },
            complete: function (jqXHR, textStatus) {                
                $(".loading-icon-stats-week").hide();
            }
        });
    }

    function updateStatResults(dateticks) {            
        $.ajax({
            type: 'POST',
            /*async: false,*/
            url: "/Statistics/ChartAJAX",
            dataType: "json",
            data: { ticks: dateticks },
            success: function (data) {
                if (data !== "") {                        
                    ctn = 0;
                    $("#datatable tbody tr").each(function () {
                        $(this).find("th").text(data[ctn].time);
                        $(this).find("td").text(data[ctn].numberOFBids);                            
                        ctn++;
                    });
                    //update dates and links
                    var m_names = new Array("January", "February", "March", 
                    "April", "May", "June", "July", "August", "September", 
                    "October", "November", "December");
                    var newdate = new Date(dateticks);                        
                    $(".bids-date-paging .current").text(newdate.getDate() + " " + m_names[newdate.getMonth()] + " " + newdate.getFullYear());
                    currentDateMostPopular = newdate;     
                    var newdatestring = newdate.getMonth()+1 + "/" + newdate.getDate() + "/" + newdate.getFullYear()
                    $( ".stat-datepicker" ).datepicker("setDate",newdatestring);                                       
                    chartStatistics();
                }
                else {
                    //console.log("Ups: empty data. Not updating");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $(".loading-icon-stats").hide();
                alert(xhr.status);
                alert(thrownError);
            },
            complete: function (jqXHR, textStatus) {
                $(".loading-icon-stats").hide();
            }
        });
    }

    function date_by_subtracting_days(date, days) {
        return new Date(
            date.getFullYear(), 
            date.getMonth(), 
            date.getDate() - days,
            date.getHours(),
            date.getMinutes(),
            date.getSeconds(),
            date.getMilliseconds()
        );
    }
    function date_by_adding_days(date, days) {
        return new Date(
            date.getFullYear(), 
            date.getMonth(), 
            date.getDate() + days,
            date.getHours(),
            date.getMinutes(),
            date.getSeconds(),
            date.getMilliseconds()
        );
    } 
});

</script>

